<template>
    <el-dialog class="ui-order-details-dialog" top="3rem" v-model="dialogVisible" title="订单详情" @opened="init" @closed="finalThings">
        <div class="ui-body-twocol">
            <div class="co-details-inf">
                <div>订单号: </div><div>{{ order.order_no }}</div>
                <div>操作员: </div><div>{{ accounts[order.operator_uid]?.realname }}</div>
                <div>购买场景: </div><div><el-text :type="sceneD[order.scene].theme">{{ sceneD[order.scene].text }}</el-text></div>
                <div>支付方式: </div><div><el-text :type="smD[order.settle_mode].theme">{{ smD[order.settle_mode].text }}</el-text></div>
                <div>订单状态: </div><div><el-text :type="stgD[order.stage].theme">{{ stgD[order.stage].text }}</el-text></div>
                <div>订单时间: </div><div><span v-datetime="order.createtime"></span></div>
                <div>订单备注: </div><div>{{ order.desc ? order.desc : '未填写' }}</div>
            </div>
            <div class="flex">
                <template v-if="goods?.length > 0">
                    <el-table :data="goods" size="small" highlight-current-row :max-height="300" border>
                        <el-table-column prop="name" label="商品图片" width="80">
                            <template #default="{row}">
                                <el-image style="width:40px; height: 40px" :src="imgUrl + row.img"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="商品名称"  show-overflow-tooltip></el-table-column>
                        <el-table-column prop="amount" label="金额" width="80" :formatter="rmbFormatter"></el-table-column>
                        <el-table-column prop="sale_price" label="销售单价" width="80"></el-table-column>
                        <el-table-column prop="num" label="销售数量" width="80"></el-table-column>
                        <el-table-column prop="refund" label="已退数量" width="80"></el-table-column>
                    </el-table>
                </template>
                <template v-if="order.stage == 2 || order.stage == 3 && distri.length > 0">
                        <div class="rack-select-bar box-row">
                            <div class="label">选择货架:</div>
                            <el-radio-group type="success" v-model="store_id" @change="onStoreSelected">
                                <template v-for="item in stores">
                                    <el-radio-button :label="item.id">{{ item.name }}</el-radio-button>
                                </template>
                            </el-radio-group>
                        </div>

                    <el-table :data="distri" size="small" highlight-current-row :max-height="300" border :row-class-name="onRowFine">
                        <el-table-column prop="name" label="商品图片" width="80">
                            <template #default="{row}">
                                <el-image style="width:40px; height: 40px" :src="imgUrl + row.img"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="商品名称"  show-overflow-tooltip></el-table-column>
                        <el-table-column prop="sale_price" label="销售单价" width="70" :formatter="rmbFormatter"  align="right"></el-table-column>
                        <el-table-column v-if="order.stage == 2 || order.stage == 3" prop="calc_price" label="金额" width="80" :formatter="rmbFormatter"  align="right"></el-table-column>
                        <el-table-column v-if="order.stage == 2 || order.stage == 3" prop="store_num" label="库存数量" width="70"  align="right"></el-table-column>
                        <el-table-column prop="num" label="购买数量" width="70" align="right"></el-table-column>
                        <el-table-column prop="done" label="已出数量" width="70" align="right">
                            <template #default="{row}">
                                <template v-if="row.done === row.num">
                                    <el-text size="small" type="success">已完成</el-text>
                                </template>
                                <template v-if="row.store_num < row.num - row.done">
                                    <el-text size="small" type="danger">库存不足</el-text>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </div>
        </div>
        <div style="padding-top: 20px;text-align: right;">
            商品总金额:  <el-text type="danger">￥{{ rmbFormat(order.amount,2) }}元</el-text>，
            实付金额:  <el-text type="danger">￥{{ rmbFormat(order.realpay,2) }}元</el-text>，
            退款金额:  <el-text type="danger">￥{{ rmbFormat(order.refund,2) }}元</el-text>
        </div>
        <template #footer>
            <div class="box-row">
                <div style="flex:1"></div>
                <el-button v-if="order.stage== 5" type="primary" @click="onReturnSales">订单退货</el-button>
                <el-button v-if="order.stage== 2 || order.stage== 3" type="primary" @click="onDistri">配货</el-button>
                <el-button v-if="order.stage== 2" type="warning" @click="onReturnSales">退款</el-button>
                <el-button type="danger" @click="onCancel">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
import { reactive, toRefs } from 'vue'
import { rmbFormat,sceneD,smD,stgD,calcGoodsFlow } from '../../uiframe/utils';
import directives from '../../uiframe/services/directives';
import { useSocket,imgUrl } from '../../uiframe/services/socket';
import { UiShowDialog } from '../../uiframe/layout/components/CompFactory.vue';
import OrderReturnSalesDialog from './OrderReturnSalesDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import DistriDialog from './DistriDialog.vue'

export default {
    directives,
    props:{
        q:Object,
        done: Function,
        _compId: Number,
        payload:Object,
        accounts:Object,
        xstores:{type:Array,default:[]}
    },
    setup(props)
    {
        let stores = props.xstores.filter(v=>v.prop == 1), payload = JSON.parse(JSON.stringify(props.payload))
        let data = reactive({
            order:payload.order,
            goods:calcGoodsFlow(payload.goods),
            distri:[],
            dialogVisible: true,
            accounts:props.accounts,
            stores,
            store_id: stores.length > 0 ? stores[0].id : 0,
            outmode:1,
        })
        const onmessage = (msg) => { ElMessage({ type: msg.success ? 'success' : 'error', message: msg.message })},
        loadDistri = ()=>{
            useSocket().then(socket=>socket.rpc('order.distri',{order_id: payload.order.id, store_id: data.store_id}, 18000).then(res=>{
                    data.distri = res.data.distri
                    if(null !== res.data.stores){
                        data.stores = stores = res.data.stores.filter(v=>v.prop == 1)
                        data.store_id = data.stores[0].id
                    }
                }).catch(res=>{
                    onmessage({success:false, message:'获取配货方案失败'})
                })
            )
        }, methods = {
            onCancel : ()=>data.dialogVisible = false,
            finalThings: ()=>{
                useSocket().then(socket=>socket.unbind('order-detail-dlg'))
                props.done()
            },
            init:()=>{},
            onSure:()=>{},
            onReturnSales:()=>{
                if(data.order.stage > 2){
                    UiShowDialog(OrderReturnSalesDialog,{payload}).then(res=>{}).catch(res=>{})
                }else{
                    let o = data.order, s = o.settle_mode, tipMsg ='';
                    
                    if(s == 4 || s == 5){
                        tipMsg = `订单未配货, 用户支付的款项将原路退回.`
                    }else if(s == 3){
                        tipMsg = `订单未配货, 请找零 ${o.realpay} 元.`
                    }else{
                        onmessage({success:false, message:'只有现金、网费、线上支付的订单可以退款.'})
                        return;
                    }

                    ElMessageBox.confirm(tipMsg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        useSocket().then(socket=>socket.rpc('refund', {order_id:o.id,goods:[]}, 18000).then(res=>{
                            onmessage(res)
                            if(res.success){
                                data.dialogVisible = false
                                props.q.resolve({success:true});
                            }
                        }).catch(res=>{
                            onmessage(res)
                        }));
                    }).catch(() => {})
                }
            },
            onStoreSelected:()=>loadDistri(),
            onRowFine:({row,index})=>{
                if(row.done === row.num){
                    return 'row-finished'
                }else if(row.store_num < (row.num - row.done)){
                    return 'row-not-enough'
                }
            },
            onDistri:()=>{
                if(data.order.stage != 2 && data.order.stage != 3){
                    onmessage({success:false, message:'只有待配货的订单可以配货.'})
                    return;
                }
                let all = data.distri.filter(v=>v.num-v.done > 0).map(v=>{return {id:v.id, num: Math.min(v.num-v.done, v.store_num),store_id:v.store_id}}),
                    distri = all.filter(v=>v.num > 0), bad = all.filter(v=>v.num <= 0)
                if(distri.length == 0){
                    onmessage({success:false, message:'没有需要配货的商品.'})
                    return;
                }
                UiShowDialog(DistriDialog,{distri, bad, id:data.order.id}).then(res=>{
                    onmessage(res);
                }).catch(res=>{});
            },
            rmbFormatter:(r,c,v)=>rmbFormat(v,2)
        }

        useSocket().then(socket=>{
            // 监听同步获得需要的数据更新, 并应用到当前对话框
            socket.watchSync('order-detail-dlg', [{
                'Documents':(n, s, p)=>n=='put' && s.order_id == payload.order.id && s.order_type == 12,_get:false,
                _next:{
                    'GoodsFlow':((n, s, p)=> n == 'put' && s.document_id == p.id), 
                    _get:true,_multi:true,
                }
            },{
                'GoodsOrder':((n, s)=>n == 'up' && s.id == payload.order.id), _get:true
            }],({GoodsFlow, GoodsOrder})=>{
                socket.rpc('order.detail',{id:payload.order.id}).then(res=>{
                    data.order = res.data.order
                    data.goods = calcGoodsFlow(res.data.goods)
                }).catch(res=>{
                    onmessage(res)
                })
            })
            // 获取配货方案数据
            if(data.order.stage == 2 || data.order.stage == 3){
                loadDistri()
            }
        })

        return {
            ...toRefs(data),
            ...methods,
            outmodes:[{label:'退款',value:1},{label:'再次出货',value:2}],
            rmbFormat,sceneD,smD,stgD, imgUrl
        }
    }
}
</script>

<style lang="scss">
.ui-order-details-dialog{
    width: 60rem;
    max-width: 60rem;
    min-width: 60rem;
    .co-details-inf{
        height: 210px;
        display: grid;
        padding-right: 10px;
        grid-template-columns: 4.5rem auto;
        grid-template-rows: repeat(1, 1.9rem);
        > *{
            line-height:1.9rem;
            &:nth-child(odd){text-align: right;padding:0 .25rem;}
        }
    }
    .el-dialog__body{
        padding: 15px 20px;
        .ui-body-twocol{
            min-height: 25rem;
        }
        .order-details{
            padding-bottom: 10px;
            line-height: 28px;
        }
        .rack-select-bar{
            padding: 0 0 .5rem 0;
            .label{
                line-height: 2rem;
                padding: 0 .5rem 0 1rem;
            }
        }
        .row-not-enough{
            background-color: #f3d7d7 !important;
        }
        .row-finished{
            background-color: #eef7ee !important;
        }
        .el-table{margin-bottom: .5rem;}
    }
}
</style>